package com.example.springcloud.gateway.filter;

import jdk.nashorn.internal.ir.debug.ClassHistogramElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @ClassName : CheckTokenFilter
 * @Description : 校验Token的全部Filter
 * @Author : tianshuo
 * @Date: 2021-05-17 22:28
 */
@Order(-1)
@Component
public class CheckTokenFilter implements GlobalFilter {
    private static final Logger logger = LoggerFactory.getLogger(CheckTokenFilter.class);
    private static final String WARNING_MSG ="Token不能为空" ;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<String> token = exchange.getRequest().getHeaders().get("Token");
        ServerHttpResponse response = exchange.getResponse();
        if (token == null) {
            logger.error("Token不能为空!");
            byte[] bits = WARNING_MSG.getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            //指定编码，否则在浏览器中会中文乱码
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }
        logger.info("Token: {}",token);
        return chain.filter(exchange);
    }
}

